package uit.comstore.model.blo;

import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import uit.comstore.model.entity.Supplier;
import uit.comstore.utils.HibernateSessionFactory;

public class SupplierBLO {
	@SuppressWarnings("unchecked")
	public List<Supplier> list() {
		List<Supplier> suppliers = null;
		Session session = HibernateSessionFactory.getSessionFactory().getCurrentSession();	
		session.beginTransaction();
		Query query = session.createQuery("from Supplier");
		suppliers = query.list();
		session.getTransaction().commit();
		return suppliers;
	}
	
	public Supplier add(Supplier supplier) {
		Session session = HibernateSessionFactory.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		session.save(supplier);
		session.getTransaction().commit();
		return supplier;
	}
	
	public Supplier getById(Long id){
		Supplier supplier = null;
		Session session = HibernateSessionFactory.getSessionFactory().getCurrentSession();	
		session.beginTransaction();
		supplier = (Supplier) session.get(Supplier.class, id);
		session.getTransaction().commit();
		return supplier;
	}
	
	public Supplier delete(Long id) {
		Session session = HibernateSessionFactory.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		Supplier supplier = (Supplier) session.load(Supplier.class, id);
		if(null != supplier) {
            session.delete(supplier);
        }
		session.getTransaction().commit();
		return supplier;
	}
	
	public Supplier update(Supplier sup){
		Session session = HibernateSessionFactory.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		Supplier supplier = (Supplier)session.get(Supplier.class, sup.getId());
		supplier.setName(sup.getName());
		supplier.setAddress(sup.getAddress());
		supplier.setEmail(sup.getEmail());
		supplier.setPhone(sup.getPhone());
		session.update(supplier);
		session.getTransaction().commit();
		session.close();
		return supplier;
	}
}
